﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using RestSharp;
using Newtonsoft.Json.Linq;
using System.Web.Services;

namespace Tradier
{
    public partial class CreateOrder : System.Web.UI.Page
    {
        public List<string> Accounts;
        public string ErrorMessage;
        public string StatusMessage;

        protected void Page_Load(object sender, EventArgs e)
        {
            var accessToken = Session["UserTradierAccessToken"];
            if (accessToken == null)
            {
                Response.Redirect("/login.aspx");
            }
            if (IsPostBack)
            {
                try
                {
                    string accountNumber = Request.Form["account_id"];
                    RestClient client = new RestClient("https://api.tradier.com");
                    var request = new RestRequest(string.Format("/v1/accounts/{0}/orders", accountNumber), Method.POST);
                    request.AddHeader("Content-type", "application/json");
                    request.AddHeader("Authorization", "Bearer " + accessToken);

                    AppendRequest(Request.Form, request);

                    var result = (client.Execute(request).Content);

                    ParseResultMessage(JObject.Parse(result));
                }
                catch (Exception)
                {
                    ErrorMessage = "Unknown";
                }
            }

            GetAccounts((string)accessToken);
        }

        private void GetAccounts(string accessToken)
        {
            Accounts = new List<string>();
            try
            {
                var client = new RestClient("https://api.tradier.com");
                var request = new RestRequest("/v1/user/profile", Method.GET);

                request.AddHeader("Authorization", "Bearer " + accessToken);
                var result = (client.Execute(request).Content);
                var json = JObject.Parse(result);

                Accounts = ParseAccountData(json);
            }
            catch
            {
                ErrorMessage = "Cannot Get Accounts";
            }
        }

        private List<string> ParseAccountData(JObject json)
        {
            var result = new List<string>();
            var accounts = json["profile"]["account"];
            if (accounts.GetType().Name == "JArray")
            {
                foreach (JObject account in accounts)
                {
                    string accountNumber = (string)account["account_number"];
                    result.Add(accountNumber);
                }
            }
            else
            {
                string accountNumber = (string)accounts["account_number"];
                result.Add(accountNumber);
            }
            return result;
        }

        private void ParseResultMessage(JObject result)
        {
            try
            {
                var errors = result["errors"];
                if (errors != null)
                {
                    foreach (JObject error in errors)
                    {
                        ErrorMessage = (string)error[0];
                    }
                    StatusMessage = "WRONG";
                }
                else
                {
                    StatusMessage = "OK";
                }
            }
            catch
            {
                ErrorMessage = "Cannot parse Result Message";
            }
        }

        private void AppendRequest(NameValueCollection nameCollection, RestRequest request)
        {
            string orderKind = nameCollection["class"];
            if (!string.IsNullOrEmpty(orderKind))
            {
                request.AddParameter("class", orderKind);
            }
            if (!string.IsNullOrEmpty(nameCollection["symbol"]))
            {
                request.AddParameter("symbol", nameCollection["symbol"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["duration"]))
            {
                request.AddParameter("duration", nameCollection["duration"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["side"]))
            {
                string side = "side";
                if (orderKind.Equals("combo"))
                {
                    side = "side[1]";
                }
                request.AddParameter(side, nameCollection["side"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["quantity"]))
            {
                string quantity = "quantity";
                if (orderKind.Equals("combo"))
                {
                    quantity = "quantity[1]";
                }
                request.AddParameter(quantity, nameCollection["quantity"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["type"]))
            {
                request.AddParameter("type", nameCollection["type"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["price"]))
            {
                request.AddParameter("price", nameCollection["price"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["stop"]))
            {
                request.AddParameter("stop", nameCollection["stop"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["option_symbol"]))
            {
                string optionSymbol = "option_symbol";
                if (orderKind.Equals("combo"))
                {
                    request.AddParameter("option_symbol[0]", "null");
                    optionSymbol = "option_symbol[1]";
                }
                request.AddParameter(optionSymbol, nameCollection["option_symbol"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["amount"]))
            {
                request.AddParameter("price", nameCollection["amount"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["multilegParams"]))
            {
                NameValueCollection multilegParams = HttpUtility.ParseQueryString(nameCollection["multilegParams"]);
                foreach (string item in multilegParams.AllKeys)
                {
                    if (item != null)
                    {
                        request.AddParameter(item, multilegParams[item]);
                    }
                }
            }
            if (!string.IsNullOrEmpty(nameCollection["comboequityside"]))
            {
                request.AddParameter("side[0]", nameCollection["comboequityside"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["comboequityquantity"]))
            {
                request.AddParameter("quantity[0]", nameCollection["comboequityquantity"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["amount"]))
            {
                request.AddParameter("price", nameCollection["amount"]);
            }
        }
    }
}